<?php
/**
 * +----------------------------------------------------------------------
 * | 管理员登录日志模型
 * +----------------------------------------------------------------------
 */
namespace app\model;

// 引入框架内置类
use app\model\Base;

class SysLoginFail extends Base
{
    protected $pk = 'ip';

    protected $schema = [
        "ip" => "varchar",  // 
        "num" => "tinyint",  // 
        "lasttime" => "int",  // 
    ];

    protected $autoWriteTimestamp = false; 

    /**
     * 检测登录 ip
     * @param string $ip 登录ip
     * @param int $time 错误时间
     * @return bool
     */
    public static function checkIp(string $ip, int $time): bool
    {
        $maxNums = 10;

        $loginFail = self::find($ip);

        return  empty($loginFail) || $time - $loginFail->time < 3600 || $loginFail->num < $maxNums ? true : false;
    }

    /**
     * 记录登录错误次数和最后错误时间
     * @param string $ip 登录ip
     * @param int $time 错误时间
     */
    public static function saveFail(string $ip, int $time)
    {
        $loginFail = self::find($ip);
        if ($loginFail) {
            $loginFail->num += 1;
            $loginFail->lasttime = $time;
        } else {
            $loginFail = new static();
            
            $loginFail->ip = $ip;
            $loginFail->num = 1;
            $loginFail->lasttime = $time;
        }
        
        $loginFail->save();
    }
}
